import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'

export default function EditUserPage() {
  const router = useRouter()
  const { id } = router.query
  const [name, setName] = useState('')

  useEffect(() => {
    if (id) {
      // 获取用户数据
      fetch(`/api/users/${id}`)
        .then(res => res.json())
        .then(data => setName(data.name))
    }
  }, [id])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    try {
      const res = await fetch(`/api/users/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name })
      })
      
      if (!res.ok) throw new Error('更新失败')
      
      alert('更新成功')
      router.push('/user')
    } catch (error) {
      alert('更新失败')
    }
  }

  return (
    <div className="p-4">
      <h1 className="text-xl font-bold mb-4">编辑用户</h1>
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block text-sm font-medium mb-1">用户名</label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            className="w-full p-2 border rounded-lg"
          />
        </div>
        <button 
          type="submit"
          className="w-full py-2 bg-blue-500 text-white rounded-lg"
        >
          保存
        </button>
      </form>
    </div>
  )
}